package com.tzxs.pay.main.bill.detail;

import android.app.Activity;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tzxs.pay.R;
import com.tzxs.pay.databinding.AutTradeItemDetailBinding;
import com.tzxs.pay.main.base.BaseActivity;
import com.tzxs.pay.main.bill.model.AutBeanDetail;
import com.tzxs.pay.main.bill.viewmodel.BillViewModel;
import com.tzxs.pay.main.print.utils.print.AidlUtil;
import com.tzxs.pay.util.StatusBarColorSetter;
import com.tzxs.pay.util.viewmodel.Callback;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * 预授权交易详情  完成
 */
public class AutTradedDetailActivity extends BaseActivity<AutTradeItemDetailBinding> {
    private ProgressDialog dialog;
    private BillViewModel model;
    private static final String TAG = AutTradedDetailActivity.class.getName();

    @Override
    protected Activity getChildActivity() {
        return this;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.aut_trade_item_detail;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarColorSetter.setStatusBarColor(this, Color.parseColor("#FAFAFA"));
        //初始化打印机
        AidlUtil.getInstance().initPrinter();
        model = ViewModelProviders.of(this).get(BillViewModel.class);
        dataBinding.setModel(model);
        dataBinding.autTradedToolbar.setTitle("");
        setSupportActionBar(dataBinding.autTradedToolbar);

        dataBinding.autTradedToolbar.setNavigationOnClickListener(v -> onBackPressed());

        model.dialogText.observe(this, new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                if (s == null) {
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                } else {
                    dialog = ProgressDialog.show(AutTradedDetailActivity.this, s, "请稍等....", false, false);
                }
            }
        });
        //通过订单号获取订单详情
        model.getAutBillDetail(getIntent().getStringExtra("orderId"),
                new Callback() {
                    @Override
                    public void success() {
                        dialog.dismiss();
                        initPage(Objects.requireNonNull(model.autDeatil.get()));
                        if (getIntent().getBooleanExtra("needPrint", false)) {
                            print(model.autDeatil.get());
                        }

                    }
                });
        //打印
        dataBinding.autTradedPrint.setOnClickListener(v -> {
            if (model.autDeatil.get() == null) {
                return;
            }
            AutBeanDetail.DataBean bean = model.autDeatil.get();
            if (bean == null) {
                return;
            }
            if (bean.getPay_status() == 2 || bean.getPay_status() == 3) {
                Toast.makeText(this, "订单未授权成功,无法打印小票", Toast.LENGTH_SHORT).show();
                return;
            }
            print(bean);
        });
    }

    //打印
    private void print(AutBeanDetail.DataBean bean) {
        List<String> printContent = Objects.requireNonNull(bean).getPrint_array();
        //String bitmapType = printContent.get(0);
        AidlUtil aidlUtil = AidlUtil.getInstance();
        if (Build.MODEL.contains("T2")) {
            String paymentMethod = printContent.get(0);
            String filename = null;
            switch (paymentMethod) {
                case "0":
                    filename = "icon_alipay.bmp";
                    break;
                case "1":
                    filename = "icon_union.bmp";
                    break;
                case "2":
                    filename = "icon_wechat.bmp";
            }
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open(filename));
                aidlUtil.printBitmap(bitmap, "0", "2", 0);
                aidlUtil.printText(printContent.get(1) + '\n', "32", "32",
                        "1", true, false);
                aidlUtil.printText(printContent.get(2) + '\n', "24", "24",
                        "1", false, false);
                String paymentMethodAndMore = printContent.get(3);
                paymentMethodAndMore = paymentMethodAndMore.replace("\\n", "\n");
                aidlUtil.printText(paymentMethodAndMore, "24", "24",
                        "0", false, false);
                String collection = printContent.get(6);
                collection = collection.replace("\\n", "\n");
                aidlUtil.printText(collection, "24", "24",
                        "0", false, false);
                String remarks = printContent.get(7);
                remarks = remarks.replace("\\n", "\n");
                aidlUtil.printText(remarks, "24", "24",
                        "0", false, false);
                aidlUtil.printQr(printContent.get(8), "6", "3");
                String cashierAndPrintingTime = printContent.get(9);
                cashierAndPrintingTime = cashierAndPrintingTime.replace("\\n", "\n");
                aidlUtil.printText(cashierAndPrintingTime, "24", "24",
                        "0", false, false);
                String last = printContent.get(10);
                last = last.replace("\\n", "\n");
                aidlUtil.printText(last, "24", "24",
                        "1", false, false);
                String repeat = printContent.get(12);
                aidlUtil.printText(repeat + "\n\n", "24", "24",
                        "1", false, false);
                aidlUtil.cutPaper(null);
            } catch (IOException ex) {
                Log.e(TAG, null, ex);
            }
        } else {
            aidlUtil.enterPrinterBuffer(true);
            String bitmapType = printContent.get(0);
            //打印支付方式图标
            commenPrint(printContent, aidlUtil, bitmapType);
//        int resId = 0;
//        resId = getResId(bitmapType);


//        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resId);
//        //打印支付方式图标
//        aidlUtil.printBitmap(bitmap, "2", "2", resId);
//        //抬头
//        aidlUtil.printText(printContent.get(1), "32", "32", "1",
//                true, false);
//        aidlUtil.printBlankLine("1", "10");
//        //门店
//        aidlUtil.printText(printContent.get(2), "24", "24", "1",
//                false, false);
//        //订单支付方式text开始
//        aidlUtil.printText(printContent.get(3).replace("\\n", "\n"),
//                "24", "24", "0",
//                false, false);
//        //业务记录
//        aidlUtil.printText(printContent.get(4), "32", "32", "0",
//                false, false);
//        //业务记录内容
//        if (!TextUtils.isEmpty(printContent.get(5))) {
//            aidlUtil.printText("\n" + printContent.get(5)
//                            .replace("\\n", "\n"), "24", "24", "0",
//                    false, false);
//        }
//        //退款 ||收款
//        aidlUtil.printText( printContent.get(6), "32", "32", "0",
//                false, false);
//        //退款获取收款内容
//        aidlUtil.printText("\n" + printContent.get(7)
//                        .replace("\\n", "\n"), "24", "24", "0",
//                false, false);
//        //打印二维码
//        aidlUtil.printQr(printContent.get(8), "8", "3");
//        //收银员
//        aidlUtil.printText(printContent.get(9).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//        //打印时间
//        aidlUtil.printText(printContent.get(10).replace("\\n", "\n"),
//                "24", "24", "0", false, false);
//        aidlUtil.printText(printContent.get(11).replace("\\n", "\n"),
//                "24", "24", "1", false, false);
//        aidlUtil.printText(printContent.get(12),
//                "24", "24", "1", false, false);
//        aidlUtil.printBlankLine("3", "50");
//        aidlUtil.printCommit();
        }
    }

    //获取到打印的图标类型
    private int getBitmapType(String type) {
        int result = -1;
        switch (type) {
            case "0":
                result = 0;
                break;

            case "1":
                result = 1;
                break;

            case "2":
                result = 2;
                break;
        }
        return result;
    }

    private void initPage(AutBeanDetail.DataBean bean) {
        String payStr = null;
        switch (bean.getPay_status()) {
            case 1:
                payStr = "未结算";

                break;
            case 2:
                payStr = "授权失败";

                break;
            case 3:
                payStr = "等待授权";
                break;
            case 4:
                payStr = "已结算";

                break;
            case 5:
                payStr = "已解冻退回";
                break;
        }
        //支付方式
        switch (bean.getPay_type()) {
            case "weixin":
                dataBinding.autTradedType.setImageResource(R.drawable.ic_wechat);
                break;
            case "alipay":
                dataBinding.autTradedType.setImageResource(R.drawable.ic_alipay);
                break;
            default:
                dataBinding.autTradedType.setImageResource(R.drawable.ic_unionpay);
                break;
        }
        dataBinding.autTradedOrderStatus.setText(payStr);
    }
}
